<?php

/**
 * @author chenxuezhi
 * @copyright 2018
 */
namespace Pwgame\Controller;
use Common\Controller\ApiController;
use Think\Model;
use Think\Log;

class IndexController extends ApiController {
    
    //const QID_UID ='pwzw:qid:%s:type:%s'; // 用户分享到群限制
    
    const GAME_TYPE = 'Pwgame';  // 游戏类型

    const QID_UID ='pwzw:user:%s:type:%s:qid:%s'; // 用户分享到群限制 %s - 字符串

    const PWZW_SHARE = "pwzws:share";  // 分享次数

    const PWZW_PLAY = "pwzws:play"; // 游戏次数

    const PWZW_AUTH_USER = "pwzws:auth_user";  // 每日新增用户

    const PWZW_TOURIST = "pwzws:tourist"; // 游戏游客用户

    const PWZW_INVITE = "pwzws:invite"; // 邀请用户次数

    const PWZW_UPGRADE = "pwzws:upgrade"; // 用户升级次数
	
	const PWZW_TEST = "pwzwtest:userid:%s"; // 用户升级次数

    const RANK_LIST = "rankList"; // 排汗榜列表

    const USER_SHARE = 'pwzwnew:share:%s:type:%s';  // 点击分享按钮的次数

    const USER_VIDEO = 'pwzwnew:video:%s:type:%s';  // 看完视频的用户

    public function __construct()
    {
        parent::__construct();

        $source = I('source','','int');  // 渠道来源
        $this->sid = $source;
    }

    // 未授权登陆
    public function loginNotAuth()
    {
        $userid = I('userid','','string'); // 用户userid
        $dateline = date('Y-m-d H:i:s');
        if(!$userid){
            $userid = uuid('Xx');
            $data =  array('userid'=>$userid,'create_time'=>$dateline);
            $ret = M('users')->add($data);

            if($ret){
                $this->countLog('pwzws',self::PWZW_TOURIST,1);  // redis记录游客次数
            }else{
                $jsons['errno'] = 1;
                $jsons['msg'] = '操作失败';
                $this->ajaxReturn($jsons);
            }
        }else{
            $users = M('users')->where("userid = '$userid'")->find();
            if($users){
                $jsons['errno'] = 0;
                $jsons['result'] = $users;
                $this->ajaxReturn($jsons);
            }else{
                $userid = uuid('Xx');
                $dateline = date('Y-m-d H:i:s');
                $data =  array('userid'=>$userid,'create_time'=>$dateline);
                $ret = M('users')->add($data);
                if($ret){
                    $this->countLog('pwzws',self::PWZW_TOURIST,1);  // 记录游客次数
                }else{
                    $jsons['errno'] = 1;
                    $jsons['msg'] = '操作失败';
                    $this->ajaxReturn($jsons);
                }
            }
        }

        $users = M('users')->where("userid = '$userid'")->find();
        $jsons['errno'] = 0;
        $jsons['result'] = $users;
        $jsons['serverTime'] = time();
        $this->ajaxReturn($jsons);
       
    }

    // 获取SessionKey
    public function getSessionKey()
    {
        $appId = C('APPID');
        $appSecret = C('APPSECRET');
        $code = I('code','','string');
                        
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid=$appId&secret=$appSecret&js_code=$code&grant_type=authorization_code";
        $opts['http'] = array('method'=>'GET', 'timeout'=>5); // 设置超时5s
        $data = @file_get_contents($url, false, stream_context_create($opts)); 
        
        $data = $data ? @json_decode($data, true) : '';
        $jsons['errno'] = 0;
        $jsons['result'] = $data;
        $this->ajaxReturn($jsons);
    }
  
    // 登陆接口
    public function login()
    {
        $appId = C('APPID');
        $appSecret = C('APPSECRET');
        $code = I('code','','string');
        $nickname = I('nickname','','string');
        $avatar = I('avatar','','string');

        if(!$code){
            $jsons['errno'] = 1;
            $jsons['msg'] = 'code不能为空';
            $this->ajaxReturn($jsons);
        }else if(empty($nickname)){
            $jsons['errno'] = 2;
            $jsons['msg'] = '昵称不能为空';
            $this->ajaxReturn($jsons);
        }else if(empty($avatar)){
            $jsons['errno'] = 3;
            $jsons['msg'] = '头像不能为空';
            $this->ajaxReturn($jsons);
        }

        $gameType = self::GAME_TYPE;
        $info = $this->wxAuthor($gameType,$code);

        $userId = isset($info['openid']) ? $info['openid'] : '';
        $map['userid'] = $userId;
        $dateline = date('Y-m-d H:i:s');
        $users = M('users')->where($map)->find();
        if(empty($users)) {
            $data = array('userid'=>$userId,'nickname'=>$nickname,'avatar'=>$avatar,'gold'=>10000,'create_time'=>$dateline);
            $ret = M('users')->add($data);
            if($ret) {
                $this->countLog('pwzws',self::PWZW_AUTH_USER,1);  // 记录新增授权用户
            }
        }else {
            M('users')->where($map)->save(array('nickname'=>$nickname,'avatar'=>$avatar));
        }

        $userInfo = M('users')->where($map)->find();

        $userInfo['good_score'] = !empty($userInfo['score']) ? $userInfo['score'] : 0;
        $userInfo['session_key'] = !empty($info['session_key']) ? $info['session_key'] : 0;
        $userInfo['serverTime'] = time();

        $this->ajaxReturn($userInfo);
    }

    // 排行榜
    public function rankingList()
    {
        $users = I('users','','string');
     
        $this->rules();
        $ret = array();
        $redis = REDIS('activity');
        $redis->select(1);

        $hash_key = self::RANK_LIST;

        $ret = $this->getRankList($hash_key,true,1,'s');
        if(empty($ret)) {
            $ret = M('users')->field('score as s,userid,nickname,avatar,id')->order('s desc')->limit(200)->select();
            $mysql = M('users')->getLastSql();
            log::write("rank:".$mysql,"SUCCESS");
            foreach($ret as $k=>$v) {
                if(!empty($v['nickname']) && !empty($v['avatar'])){
                    $id = $v['id'];
                    $flag = $redis->hSet($hash_key,$id, json_encode($v));
                }
            }
        }

        $jsons['errno'] = 0;
        $jsons['result'] = $ret;
    
        $this->ajaxReturn($jsons);
    }

    // 排行榜限制范文
    public function rules() {
        $redis = REDIS('activity');
        $redis->select(1);
        $ip = get_client_ip();
        $userKey = 'ipuser:%s:api_count';
        $key = sprintf($userKey,$ip);  //用户主键分享到群
        $check = $redis->exists($key);

        if($check){
            $redis->incr($key);  //键值递增
            $count = $redis->get($key);  
            if($count > 2){ 
                $jsons['errno'] = 0;
                $jsons['result'] = array();
                $this->ajaxReturn($jsons); 
                //exit('your have too many request');  
            }  
        }else{  
            $redis->incr($key);  
            //限制时间为60秒   
            $redis->expire($key,1); 
        } 
    }

    // 游戏复活
    public function revive()
    {
        $userid = I('userid','','string'); // 用户userid
        $gold = I('gold',0,'string'); // 复活金币
        
        $map['userid'] = $userid; 
        if(!$userid){
            $jsons['errno'] = 1;
            $jsons['msg'] = '用户userid不能为空';
        }else if(empty($gold)){
            $jsons['errno'] = 2;
            $jsons['msg'] = '复活金币不能为空';
        }else if(!$users = M('users')->where($map)->find()){
            $jsons['errno'] = 3;
            $jsons['msg'] = '用户不存在';
        }else if($users['gold'] < $gold){
            $jsons['errno'] = 4;
            $jsons['msg'] = '金币不足';
        }else{
            $ret = M('users')->where($map)->setDec('gold',$gold);
            
            if($ret){
                $jsons['errno'] = 0;
                $jsons['msg'] = '操作成功';
            }else{
                $jsons['errno'] = 5;
                $jsons['msg'] = '操作失败';
            }
        }
        $this->ajaxReturn($jsons);   
    }

    // 记录用户点击分享按钮的次数
    public function setShare() {
        $userid = I('userid','','string'); // 用户userid
        $type = I('type',1,'int');  // 1:分享次数 2：分享完成(暂停) 3：看完视频次数 4：点击视频次数
        $redis = REDIS('activity');
        $userKey = sprintf(self::USER_SHARE,$userid,$type);  //用户主键分享到群

        $arr = array(1=>'shareNum',3=>'endvedio',4=>'vedioNum');
        $typeName = $arr[$type];

        $this->countLog('pwzws','pwzws:'.$typeName);  // 记录看完视频的次数
       
        $this->response(0,'ok');  
    }

    // 记录用户点击分享按钮的次数
    private function _setShare($userid,$type) {
        $redis = REDIS('activity');
        $redis->select(5);
        $userKey = sprintf(self::USER_SHARE,$userid,$type);  // 1:分享完成 2：已废弃 3：看完视频次数 4：点击视频次数
        if($type == 1 || $type == 3) { 
            $redis->incrBy($userKey,1);
            $redis->exprieAt($userKey,strtotime(date('Y-m-d 23:59:59'))); // 每日23点59分过期
        }
    }
    
    // 分享奖励
    public function shareAward()
    {
        $shareType = I('shareType',1,'int'); // 分享类型(1首页，2升级(已取消) 3:看视频)
        $userid = I('userid','','string'); // 用户userid
        $gold = I('gold',0,'string'); // 金币
        
        if(empty($userid)) {
            $jsons = array('errno'=>2,'msg'=>'用户不存在');           
            $this->ajaxReturn($jsons);
        }

        if(empty($gold)){
            $jsons = array('errno'=>1,'msg'=>'金币不能为空');           
            $this->ajaxReturn($jsons);
        }
        
    
        $map['userid'] = $userid;      
        // 增加金币
        $ret = M('users')->where($map)->setInc('gold',$gold);
        
        // 分享记录
        $data['userid'] = $userid;
        $data['share_type'] = $shareType;
        $data['create_time'] = date('Y-m-d H:i:s');
        $ret2 = M('users_share_log')->add($data);

        $this->_setShare($userid,$shareType);


        $jsons = array('errno'=>0,'msg'=>'分享成功');
        $this->ajaxReturn($jsons);

        // switch($shareType){
        //     case 1: // 首页分享
                
        //         break;

        //     case 3: // 视频分享         
        //         $map['userid'] = $userid;      
        //         // 增加金币
        //         $ret = M('users')->where($map)->setInc('gold',$gold);
                
        //         // 分享记录
        //         $data['userid'] = $userid;
        //         $data['share_type'] = $shareType;
        //         $data['create_time'] = date('Y-m-d H:i:s');
        //         $ret2 = M('users_share_log')->add($data);

        //         $this->setShare($userid,$shareType);
        //         $jsons = array('errno'=>0,'msg'=>'看完视频成功');
        //         $this->ajaxReturn($jsons);
        //         break;
        // }
    }
    
    // 获取用户信息
    public function getUserInfo(){

        $userid = I('userid','','string');
        if(!$userid){
            $jsons['errno'] = 1;
            $jsons['msg'] = '用户userid不能为空';
            $this->ajaxReturn($jsons);
        }

        $map['userid'] = $userid;
        $users = M('users')->where($map)->find();
        if($users){
            
            // 用户最优成绩
            //$ret = M('users_game_result')->where($map)->order('score desc')->find();
            $users['good_score'] = !empty($users['score']) ? $users['score'] : 0;

            $redis = REDIS('activity');
            $redis->select(1);

            $shareKey = sprintf(self::USER_SHARE,$userid,1);  //分享键
            $vedioKey = sprintf(self::USER_SHARE,$userid,3);  //视频键
           
            $share = $redis->get($shareKey);
            $vedio = $redis->get($vedioKey);
            
            $share_count = array(1=>intval($share), 3=>intval($vedio));
       
            $users['share_count'] = $share_count;
            //echo M()->getLastSql();
            
            $jsons['errno'] = 0;
            $jsons['result'] = $users;
        }else{
            $jsons['errno'] = 1;
            $jsons['msg'] = '用户不存在';
        }

        $this->ajaxReturn($jsons);
    }
    
    // 解密数据
    public function cryptData()
    {
        $appid = C('APPID'); // Appid
        $sessionKey = I('sessionKey','','string'); // sessionKey
        $encryptedData = I('encryptedData','','string'); // 加密数据
        $iv = I('iv','','string');// 与用户数据一同返回的初始向量
        $userid = I('userid','','string'); // 用户userid
        $type = I('type',0,'int'); // 分享类型(1普通分享，2分享复活)

        if(empty($userid)){
            $jsons['errno'] = 1;
            $jsons['msg'] = '用户userid不能为空';
            $this->ajaxReturn($jsons);
        }

        $pc = new \Org\Util\WXBizDataCrypt($appid, $sessionKey);
        $errCode = $pc->decryptData($encryptedData, $iv, $data);//对微信小程序用户加密数据的解密
        
        $data = $data ? json_decode($data, true) : '';
        $openGId = isset($data['openGId']) ? $data['openGId'] : 0;
        
        if ($errCode == 0) {  // 解密成功

            $redis = REDIS('activity');
            $redis->select(1);
            $evening = date('Y-m-d 23:59:59'); //每日23点59分

            //$userKey = sprintf(self::QID_UID,$userid,$type);  //用户主键分享到群
            $userKey = sprintf(self::QID_UID,$userid,$type,$openGId);  //用户主键分享到群

            $shareKey = $redis->get($userKey);

            if( $type == 2 && $shareKey == 1  ) {
                $this->response(2,'每局同一群只能分享一次');
            }

            if( $type == 1 && $shareKey == 1  ) {
                $this->response(3,'每天同一群只能分享一次');
            }

            $redis->set($userKey,1);  // 标记
            $redis->exprieAt($userKey,strtotime(date('Y-m-d 23:59:59'))); // 每日23点59分过期

            // 群分享记录
            $groups = array(
                'userid' => $userid,
                'gid' => $openGId,
                'type'=> $type,
                'create_time'=>date('Y-m-d H:i:s')
            );
            $ret = M('share_group_log')->add($groups);

            $this->countLog('pwzws',self::PWZW_SHARE,1);  // 记录分享次数日志

            $jsons['errno'] = 0;
            $jsons['msg'] = '成功解密';
            $jsons['result'] = $data;
            $this->ajaxReturn($jsons);
        }else {
            $jsons['errno'] = $errCode;
            $jsons['msg'] = '解密失败';
            $this->ajaxReturn($jsons);
        }
            
        // $data['shareState'] = false;
        // // 群分享记录
        // $groups['userid'] = $userid;
        // $groups['gid'] = $openGId;
        // $groups['type'] = $type;
        // $groups['create_time'] = date('Y-m-d H:i:s');
        // if($ret = M('share_group_log')->add($groups)){
        //     $data['shareState'] = true;
        // }
    }

    public function test2() {
        $redis = REDIS('activity');
        $redis->select(1);
        $map['id'] = 19;
        $map['userid'] = 'oRxAc5Jk6_pHjuvIyaFhj1w9C3Zg'; // ->field('nickname')->where($map)->find();
        $ret = M('users');
        $list = array('list'=>'list','abc'=>'123456');
        echo '1111';
        print_r($list);
        exit;
    }
    
    // 获取用户邀请
    public function getUserInvite()
    {
        $userid = I('userid','','string'); 
        $start_time = date('Y-m-d 00:00:00'); // 开始时间
        $end_time = date('Y-m-d 23:59:59'); // 结束时间

        $map['userid'] = $userid;
        $map['left(create_time,10)'] = date('Y-m-d');
        $list = M('users_invite')->field('id,invited_userid,create_time')->where($map)->order('id asc')->select();
        if(empty($list)) {
            $jsons = array('errno'=>0,'result'=>"");
            $this->ajaxReturn($jsons);
        }

        $uidArr = array_column($list,'invited_userid');
        $timeArr = array_column($list,'create_time','invited_userid');
        $uidStr = implode(',', $uidArr);

        $where['userid'] = array('in',$uidStr);

        $str = null;
        foreach($uidArr as $k=>$v) {
            $str .= "'$v',";
        }
        $strs = rtrim($str,',');
        $userInfo = M('users')->field('id,userid,nickname,avatar')->where($where)->order('field(userid,'.$strs.')')->select();

        foreach($userInfo as $k=>$v) {
            $userInfo[$k]['create_time'] = $timeArr[$v['userid']];
        }

        // $map['I.userid'] = $userid;
        // $map['I.create_time'] = array('BETWEEN',array($start_time, $end_time));
        // $inviteList = M('users_invite')->alias('I')
        //     ->field('U.userid, U.nickname, U.avatar, I.create_time')
        //     ->join('INNER JOIN c_users U ON U.userid = I.invited_userid')
        //     ->where($map)
        //     ->select();
         
        $jsons['errno'] = 0;
        $jsons['result'] = $userInfo ? $userInfo : '';
        $this->ajaxReturn($jsons);
    }

    // 清理邀请记录
    public function removeRecord() {
        $userid = I('userid','','string');

        $date = date('Y-m-d');
        $map['userid'] = $userid;
        $map['left(create_time,10)'] = $date;
        $ret = M('users_invite')->where($map)->delete();

        if($ret) {
            $jsons['errno'] = 0;
            $jsons['msg'] = '操作成功';
            $this->ajaxReturn($jsons);
        }
        $jsons['errno'] = 1;
        $jsons['msg'] = '操作失败';
        $this->ajaxReturn($jsons);
    }
    
    
    // 邀请记录
    public function inviteRecord()
    {
        $userid = I('userid','','string');
        $invited_userid = I('invited_userid','','string');
        $start_time = date('Y-m-d 00:00:00'); // 开始时间
        $end_time = date('Y-m-d 23:59:59'); // 结束时间
        
        $map['userid'] = $userid;
        $map['invited_userid'] = $invited_userid;
        $map['create_time'] = array('BETWEEN',array($start_time, $end_time));
        
        
        if(empty($invited_userid) || $invited_userid == 'undefined'){
            $jsons['errno'] = 1;
            $jsons['msg'] = '被邀请人userid不能为空';
            $this->ajaxReturn($jsons);
        }else if($userid == $invited_userid){
            $jsons['errno'] = 2;
            $jsons['msg'] = '不能邀请自己';
            $this->ajaxReturn($jsons);
        }else if($ret = M('users_invite')->where($map)->find()){ 
            $jsons['errno'] = 3;
            $jsons['msg'] = '已被邀请过';
            $this->ajaxReturn($jsons);
        }else{
            $data['userid'] = $userid;
            $data['invited_userid'] = $invited_userid;
            $data['create_time'] = date('Y-m-d H:i:s');
            $ret = M('users_invite')->add($data);
            if($ret){
                
                $this->countLog('pwzws',self::PWZW_INVITE,1);  // 记录邀请次数

                $jsons['errno'] = 0;
                $jsons['msg'] = '邀请成功';
                $this->ajaxReturn($jsons);
            }else{
                $jsons['errno'] = 4;
                $jsons['msg'] = '邀请失败';
                $this->ajaxReturn($jsons);
            }
        }
    }
    
    // 离线金币领取
    public function getGameGold()
    {
        $userid = I('userid','','string');
        $gold = I('gold',0,'string');
        
        $map['userid'] = $userid;
        $data['offline_time'] = 0;
        $data['gold'] = array('exp',"gold + $gold");
        $ret = M('users')->where($map)->save($data);
        if($ret){
            $jsons['errno'] = 0;
            $jsons['msg'] = '操作成功';
            $this->ajaxReturn($jsons);
        }else{
            $jsons['errno'] = 1;
            $jsons['msg'] = '操作失败';
            $this->ajaxReturn($jsons);
        }
    }
    
    // 设置金币
    public function setGold()
    {
        $userid = I('userid','','string'); // 用户userid
        $type = I('type','inc','string'); // 操作类型：inc增加，dec减少
        $gold = I('gold',0,'string'); // 金币
        
        $map['userid'] = $userid;
        
        if(!$userid){
            $jsons['errno'] = 1;
            $jsons['msg'] = '用户userid不能为空';
            $this->ajaxReturn($jsons);
        }else if(!$users = M('users')->where($map)->find()){
            $jsons['errno'] = 2;
            $jsons['msg'] = '用户不存在';
            $this->ajaxReturn($jsons);
        }else if($gold < 0){
            $jsons['errno'] = 3;
            $jsons['msg'] = '金币不能小于0';
            $this->ajaxReturn($jsons);
        }else if($type == 'dec' && $users['gold'] < $gold){
            $jsons['errno'] = 4;
            $jsons['msg'] = '金币不足';
            $this->ajaxReturn($jsons);
        }else if($type == 'dec'){ // 减少
            $ret = M('users')->where($map)->setDec('gold', $gold);
            if($ret){
                $jsons['errno'] = 0;
                $jsons['msg'] = '扣减成功';
            }else{
                $jsons['errno'] = 5;
                $jsons['msg'] = '扣减失败';
            }
            $this->ajaxReturn($jsons);
        }else if($type == 'inc'){ // 增加
            $ret = M('users')->where($map)->setInc('gold', $gold);
            if($ret){
                $jsons['errno'] = 0;
                $jsons['msg'] = '增加成功';  
            }else{
                $jsons['errno'] = 6;
                $jsons['msg'] = '增加失败';
            }
            $this->ajaxReturn($jsons);
        }else{
            $jsons['errno'] = 7;
            $jsons['msg'] = '操作类型不正确';
            $this->ajaxReturn($jsons);
        }
    }
    
    // 清除群分享日志
    public function clearGroupLog()
    {
        $userid = I('userid','','string');  // 用户编号
        $type = I('type',2,'int');  // 1:普通分享 2：分享到群限制分享
        
        if($userid && $type) {
            $redis = REDIS('activity'); 
            $redis->select(1);

            $userKey = sprintf(self::QID_UID,$userid,$type,'*');  //用户主键分享到群
            $delKey = $redis->keys($userKey);
            $redis->del($delKey);  
            // $userKey = sprintf(self::QID_UID,$userid,$type);  //用户主键分享到群
            // $redis->del($userKey);
        } 
        
        $this->countLog('pwzws',self::PWZW_PLAY,1);  // 记录玩游戏次数

        $jsons['errno'] = 0;
        $jsons['msg'] = '操作成功';
        $this->ajaxReturn($jsons);
    }
    
    // 向房间推送消息
    public function pushMsg()
    {
        $roomId = I('roomId','','string'); // 切记字符类型
        $state = I('state',1,'int'); // 1好友加入, 2开始游戏, 3放弃游戏, 4同步游戏界面
        $msg = I('msg','','string');
        $plus = I('plus','','string');
        $channel = I('channel','','string'); // 渠道
        
        $contents['channel'] = $channel;
        $contents['roomId'] = $roomId;
        $contents['state'] = $state;
        $contents['msg'] = $msg;
        $contents['plus'] = $plus;   
        
        $sendMsg = $this->sendMsg($contents);
        $sendMsg = str_replace("\n",'',$sendMsg);
        
        $jsons['state'] = $sendMsg;
        $this->ajaxReturn($jsons);
    }
    
    // Socket发送数据
    private function sendMsg($contents)
    {
        // 建立socket连接到内部推送端口
        $client = stream_socket_client('tcp://127.0.0.1:5678', $errno, $errmsg, 1);
        // 推送的数据，包含uid字段，表示是给这个uid推送
        
        // 发送数据，注意5678端口是Text协议的端口，Text协议需要在数据末尾加上换行符
        fwrite($client, json_encode($contents)."\n");
        // 读取推送结果
        return fread($client, 8192);  
    }
    
    // 记录游戏成绩
    public function addGameResult()
    {
        $userid = I('userid','','string');
        $score = I('score','','string');
        $nickname = I('nickname','','string');
        $avatar = I('avatar','','string');
        
        if(strlen($userid) == 30){
            $jsons['errno'] = 1;
            $jsons['msg'] = '游客不记录成绩';
            $this->ajaxReturn($jsons);
        }else if($userid == 'undefined' || $nickname == 'undefined' || $avatar == 'undefined'){
            $jsons['errno'] = 2;
            $jsons['msg'] = '字段不能为undefined';
            $this->ajaxReturn($jsons);
        }else if(!$userid){
            $jsons['errno'] = 3;
            $jsons['msg'] = '用户userid不能为空';
            $this->ajaxReturn($jsons);
        }else if(empty($score)){
            $jsons['errno'] = 4;
            $jsons['msg'] = '用户成绩不能为空';
            $this->ajaxReturn($jsons);
        }else{
			$map['userid'] = $userid;
			$data1['score'] = $score;
			$data1['update_time'] = date('Y-m-d H:i:s');

            $redis = REDIS('activity');
            $hashKey = self::RANK_LIST;

			$res = M('users')->field('score,id,nickname,avatar,userid')->where($map)->find();
   
            $data = array('id'=>$res['id'],'s'=>$score,'userid'=>$res['userid'],'nickname'=>$res['nickname'],'avatar'=>$res['avatar']);
            
            $this->setRankList($hashKey,1,$data,$res['id'],'s',$score);
            
			if($score > $res['score']) {
				M('users')->where($map)->save($data1);
			}
			
			$jsons['errno'] = 0;
			$jsons['msg'] = '添加成功';
			$this->ajaxReturn($jsons);			                           
        }
    }

    // 用户登录游戏跟新数据
    public function upgrade() {
        $userid = I('userid','','string');
        $gold = I('gold',0,'string');  //金币
        $bullet_level = I('bullet_level',0,'int');  // 子弹等级
        $fire_level = I('fire_level',0,'int');  // 火力等级
        $game_time_level = I('game_time_level',0,'int'); //游戏金币掉落等级
        $offline_time_level = I('offline_time_level',0,'int'); // 离线领金币等级
		
        if(!$userid){
            $jsons['errno'] = 2;
            $jsons['msg'] = '用户userid不能为空';
            $this->ajaxReturn($jsons);
        }
        $data = array();
        $map['userid'] = $userid;
        $field = 'gold,bullet_level,fire_level,game_time_level,offline_time_level,id,nickname';
        $userInfo = M('users')->field($field)->where($map)->find();
    
        $redis = REDIS('activity');
        $redis->select(1);
        $userKey = 'offline:user:'.$userid;
        $offline_time = $redis->get($userKey);

        if($bullet_level > $userInfo['bullet_level'] || $fire_level > $userInfo['fire_level'] || $game_time_level > $userInfo['game_time_level'] || $offline_time_level > $userInfo['offline_time_level'] || $gold != $userInfo['gold'] || $offline_time > 0 ) {
            
            $data = array(
                'bullet_level' => $bullet_level,
                'fire_level'  => $fire_level,
                'game_time_level' => $game_time_level,
                'offline_time_level' => $offline_time_level
            );

            $data['gold'] = $gold;
            $where['id'] = $userInfo['id'];

            if(!empty($offline_time)) {
                $data['offline_time'] = array('exp',"offline_time + $offline_time");
            }
        
            $ret = M('users')->where($where)->save($data);

            if(!empty($data['offline_time'])) {
                $redis->del($userKey);
            }

            //$times = date("Y-m-d H:i:s");
            //$str = '用户编号:'.$userInfo['id'].'用户昵称:'.$userInfo['nickname'].'跟新时间:'.$times.'金币数:'.$gold.'子弹等级:'.$bullet_level.'火力等级:'.$fire_level.'掉落金币：'.$game_time_level.'领金币等级:'.$offline_time_level;

            //Log::write('upgrade:'.$str,'SUCCESS');

            $this->countLog('pwzws',self::PWZW_UPGRADE,1);  // 升级成功次数
        }
        
        $jsons['errno'] = 0;
        $jsons['msg'] = '操作成功';
        $this->ajaxReturn($jsons);   
    }
    
}